package com.example.codegen.resolver;

import com.example.codegen.mapper.OracleMapper;
import com.example.codegen.model.Column;
import com.example.codegen.model.Datasource;
import com.example.codegen.model.Table;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class OracleResolver implements BaseResolver {

    @Autowired
    public OracleResolver() {
    }

    @Override
    public SqlSession getSession(Datasource datasource) {
        Configuration configuration = getConfiguration(datasource);
        XMLMapperBuilder oracleXmlMapperBuilder = new XMLMapperBuilder(this.getClass().getClassLoader().getResourceAsStream("mapper/OracleMapper.xml"), configuration, "Oracle", configuration.getSqlFragments());
        oracleXmlMapperBuilder.parse();
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
        SqlSession session = sqlSessionFactory.openSession();
        return session;
    }

    @Override
    public String getVersion(Datasource datasource) {
        SqlSession session = getSession(datasource);
        OracleMapper oracleMapper = session.getMapper(OracleMapper.class);
        String version = oracleMapper.getVersion();
        session.close();
        return version;
    }

    @Override
    public List<Table> getTables(Datasource datasource) {
        SqlSession session = getSession(datasource);
        OracleMapper oracleMapper = session.getMapper(OracleMapper.class);
        List<Table> tables = oracleMapper.getTables(datasource.getDatabaseName(), datasource.getSchemaName(), null);
        session.close();
        return tables;
    }

    @Override
    public Table getTable(Datasource datasource, String tableName) {
        SqlSession session = getSession(datasource);
        OracleMapper oracleMapper = session.getMapper(OracleMapper.class);
        List<Table> tables = oracleMapper.getTables(datasource.getDatabaseName(), datasource.getSchemaName(), tableName);
        session.close();
        return tables.size() == 0 ? null : tables.get(0);
    }

    @Override
    public List<Column> getColumns(Datasource datasource, String tableName) {
        SqlSession session = getSession(datasource);
        OracleMapper oracleMapper = session.getMapper(OracleMapper.class);
        List<Column> columns = oracleMapper.getColumns(datasource.getDatabaseName(), datasource.getSchemaName(), tableName);
        session.close();
        return columns;
    }
}
